package com.lock;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁
 * 读锁与读锁不互斥
 * 写锁与写锁互斥
 * 读锁与写锁互斥
 */
public class Demo06 {

    public static void main(String[] args) {
        MyService service = new MyService();

        Demo05ThreadA demo05ThreadA = new Demo05ThreadA(service);
        demo05ThreadA.setName("A");
        demo05ThreadA.start();
        Demo05ThreadB demo05ThreadB = new Demo05ThreadB(service);
        demo05ThreadB.setName("B");
        demo05ThreadB.start();
    }
}

class MyService {
    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    public void read() {
        try {
            try {
                lock.readLock().lock();
                System.out.println(Thread.currentThread().getName() + "获得读锁:" + System.currentTimeMillis());
                Thread.sleep(3000);
            } finally {
                lock.readLock().unlock();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void write() {
        try {
            try {
                lock.writeLock().lock();
                System.out.println(Thread.currentThread().getName() + "获得写锁:" + System.currentTimeMillis());
                Thread.sleep(3000);
            } finally {
                lock.writeLock().unlock();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class Demo05ThreadA extends Thread {
    private MyService service;

    public Demo05ThreadA(MyService service) {
        super();
        this.service = service;
    }

    @Override
    public void run() {
        super.run();
        service.read();
        service.write();
    }
}

class Demo05ThreadB extends Thread {
    private MyService service;

    public Demo05ThreadB(MyService service) {
        super();
        this.service = service;
    }

    @Override
    public void run() {
        super.run();
        service.read();
        service.write();
    }
}